<template>
  <div>
    <el-card style="position: relative; min-width: 1200px">
      <div v-if="eventTab == '1'" class="tableSelectWrap">
        <el-form ref="salesOrderForm" :model="commandForm" label-width="100px">
          <el-row>
            <el-col :span="7" style="display: flex">
              <el-form-item label-width="0" prop="dateType">
                <el-select
                  v-model="commandForm.dateType"
                  style="width: 100px; border-radius: 0px"
                  placeholder="选择时间"
                  class="leftSelect"
                >
                  <el-option label="创建时间" value="1"></el-option>
                  <el-option label="支付时间" value="2"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label-width="0" prop="date" style="flex: 1">
                <el-date-picker
                  :default-time="['00:00:00', '23:59:59']"
                  v-model="commandForm.date"
                  style="width: 100%; border-radius: 0px; margin-top: 1px"
                  type="datetimerange"
                  :clearable="false"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="7" :offset="1">
              <el-form-item label="支付状态" prop="status">
                <el-select
                  v-model="commandForm.status"
                  style="width: 100%"
                  placeholder="请选择订单状态"
                  clearable
                >
                  <el-option
                    v-for="item of payStateList"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7" :offset="1">
              <el-form-item label="退款状态" prop="refundState">
                <el-select
                  v-model="commandForm.refundState"
                  style="width: 100%"
                  placeholder="请选择订单状态"
                  clearable
                >
                  <el-option
                    v-for="item of refundStateList"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
       <el-col :span="7">
            <el-form-item label="收款方" prop="memberId">
              <el-select
                  v-model="commandForm.memberId"
                  style="width: 100%"
                  placeholder="请选择收款方"
                  clearable
                >
                <el-option
                    v-for="item of merchaList"
                    :key="item.id"
                    :label="item.memberName"
                    :value="item.id"
                  ></el-option>
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="1">
            <el-form-item label="服务方" prop="serviceMerchantId">
              <el-select
                  v-model="commandForm.serviceMerchantId"
                  style="width: 100%"
                  placeholder="请选择服务方"
                  clearable
                >
                <el-option
                    v-for="item of merchaList"
                    :key="item.id"
                    :label="item.memberName"
                    :value="item.id"
                  ></el-option>
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="1" style="min-width: 170px">
              <el-button class="width120" @click="this.resetFields"
                >重置</el-button
              >
              <el-button
                type="primary"
                class="width120"
                @click="
                  () => {
                    this.dataForm = JSON.parse(
                      JSON.stringify(this.commandForm)
                    );
                    this.handleQuery();
                  }
                "
                >查询</el-button
              >
            </el-col>
          </el-row>
          <el-row>
            <el-button
              @click="exchangeEventTab"
              icon="el-icon-search"
              class="searchBtn"
              >精确搜索</el-button
            >
          </el-row>
        </el-form>
      </div>
      <div v-if="eventTab == '2'" class="tabWrap">
        <el-input
          class="search"
          clearable
          v-model="commandForm.payformNo"
          placeholder="请输入商户订单号/商品名称/渠道流水号/云尘付流水号"
          @keyup.enter.native="
            () => {
              this.dataForm = JSON.parse(JSON.stringify(this.commandForm));
              this.globalQuery();
            }
          "
        >
          <!-- <i slot="prefix" class="el-input__icon el-icon-search-outlined"></i> -->
        </el-input>
        <div class="searBtn">
          <el-button
            type="primary"
            @click="
              () => {
                this.dataForm = JSON.parse(JSON.stringify(this.commandForm));
                this.globalQuery();
              }
            "
            >搜索</el-button
          >
        </div>
        <div class="backWrap" @click="exchangeEventTab">
          <span>筛选搜索</span>
          <img src="@/assets/imgs/setting/down1.png" />
        </div>
      </div>
    </el-card>
    <el-card
      class="textBox"
      style="min-width: 1200px; margin-bottom: -5px; margin-top: 15px"
    >
      <span class="numBox">
        <span>订单金额</span>
        <span class="symbol">￥</span>
        <span class="num">{{ info.fmtOrderTotalAmount || 0.0 }}</span>
      </span>
      <span class="numBox">
        <span>已支付</span>
        <span class="symbol">￥</span>
        <span class="num">{{ info.fmtPayTotalAmount || 0.0 }}</span>
      </span>
      <span class="numBox">
        <span>已退款</span>
        <span class="symbol">￥</span>
        <span class="num">{{ info.fmtRefundTotalAmount || 0.0 }}</span>
      </span>
    </el-card>
    <el-card style="margin-top: 20px; min-width: 1200px">
      <div class="switch">
        <div>
          <el-switch v-model="isFixedTableH" inactive-text="固定表头">
          </el-switch>
        </div>
      </div>
      <el-table
        :data="dataList"
        :height="fixedTableHeight"
        @selection-change="handleSelectionChange"
      >
        <template slot="empty">
          <el-empty
            :image="require('@/assets/imgs/middleWork/k1.png')"
            :image-size="80"
            description="暂无相关数据"
          ></el-empty>
        </template>
        <el-table-column
          show-overflow-tooltip
          prop="gmtCreated"
          width="180"
          align="center"
          label="创建时间"
        >
          <template slot-scope="scope">
            <div
              style="
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              "
            >
              {{ scope.row.gmtCreated ? scope.row.gmtCreated : "-" }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="gmtCreated"
          width="180"
          align="center"
          label="支付时间"
        >
          <template slot-scope="scope">
            <div
              style="
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              "
            >
              {{ scope.row.gmtCreated ? scope.row.gmtCreated : "-" }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="merchantOrderNo"
          align="center"
          label="商户订单号"
        >
          <template slot-scope="scope">
            <div
              style="
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              "
            >
              {{ scope.row.merchantOrderNo ? scope.row.merchantOrderNo : "-" }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="subject"
          align="center"
          label="商品名称"
        >
          <template slot-scope="scope">
            <div
              style="
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              "
            >
              {{ scope.row.subject ? scope.row.subject : "-" }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="fmtOriginalAmount"
          align="center"
          label="订单金额/元"
        >
          <template slot-scope="scope">
            <div
              style="
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              "
            >
              {{
                scope.row.fmtOriginalAmount ? scope.row.fmtOriginalAmount : "-"
              }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="statusName"
          align="center"
          label="支付状态"
        >
          <template slot-scope="scope">
            <div
              style="
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              "
            >
            {{    scope.row.statusName ? scope.row.statusName : "-"}}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="refundStatusName"
          align="center"
          label="退款状态"
        >
          <template slot-scope="scope">
            <div
              style="
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              "
            >
              <span>
                {{    scope.row.refundStatusName ? scope.row.refundStatusName : "-"}}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="address"
          align="center"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="handleDetails(scope.row)"
              >详情</el-button
            >
            <el-button type="text" v-if="scope.row.refundButton" @click="refundMoney(scope.row)"
              >退款</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-pagination
      layout="prev, pager, next, sizes, jumper"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      :current-page="pageNum"
      :total="total"
      @current-change="pageCurrentChangeHandle"
      @size-change="pageSizeChangeHandle"
    >
    </el-pagination>
    <!-- 详情抽屉 -->
    <detail-drawer
      :drawer.sync="drawer"
      :info="detailsInfo"
      :activeKey="activeKey"
    ></detail-drawer>
    <el-dialog
      title=""
      class="tkDialog"
      :visible="refundDialog"
      width="449px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="dialogTitle">退款申请</div>
      <el-form
        :model="form"
        ref="refundForm"
        label-position="top"
      >
      <el-form-item label="商户订单号" prop="merchantOrderNo">
          <el-input
            v-model="form.merchantOrderNo"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="
            '退款金额' 
          "
          prop="refundAmount"
        >
          <el-input
          disabled
            type="number"
            v-model="form.refundAmount"
            :placeholder="'退款金额不可超过'+ (
              (this.refundRow.fmtActualAmount - this.refundRow.fmtRefundAmount).toFixed(2)
            ) +
            '元)'"
            :step="0.01"
            oninput="if(isNaN(value)) { value = parseFloat(value) } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="退款理由" prop="refundRemark">
          <el-input
            v-model="form.refundRemark"
            maxlength="30"
            placeholder="输入退款理由"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="分润信息" v-if="this.refundRow.settleWay!='not'">
       <div style="width: 100%;
background: rgba(240,240,240,0.5);padding:10px;">
<ul style="margin-bottom:10px;" v-for="item,index in settleList" :key="index">
  <li>
    <span style="display:inline-block;width:100px;color:#869DAA;">分润接收方</span><span>商户A</span>
  </li>
  <li>
  <span style="display:inline-block;width:100px;color:#869DAA;">分润金额</span><span>￥5.00</span>
  </li>
  <li>
   <span style="display:inline-block;width:100px">退款金额</span><span>￥5.00</span>
  </li>
</ul>
</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          @click="
            refundDialog = false;
            $refs['refundForm'].resetFields();
          "
          class="width120"
          >取消</el-button
        >
        <el-button type="primary" class="width120" @click="confirmRefund"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import detailDrawer from "./detailDrawer.vue";
import mixin from "@/mixins/mixin";
import { mapMutations } from "vuex";
export default {
  name: "salesOrder",
  mixins: [mixin],
  components: {
    detailDrawer,
  },
  data() {
    return {
      settleList:[
        {},{}
      ],
      activeKey: "1",
      buttonRole: false,
      mixinViewModuleOptions: {
        getDataListURL: "/api/order/listByPage",
        createdIsNeed: false,
      },
      detailsInfo: {},
      drawer: false,
      refundRow: {},
      form: {
        refundRemark: "",
        refundAmount: "",
        merchantOrderNo:'',
      },
      refundDialog: false,
      payformId: null,
      commandForm: {
        status: "",
        refundState: "",
        memberId: "",
        serviceMerchantId: "",
        payformNo: "",
        dateType: "1",
        date: [
          this.$moment().startOf("day").format("YYYY-MM-DD HH:mm:ss"),
          this.$moment().endOf("day").format("YYYY-MM-DD HH:mm:ss"),
        ],
      },
      dataList: [],
      info: {},
      payStateList: [
        // 支付状态
        { id: 1, label: "所有", value: "" },
        { id: 2, label: "未支付", value: "created" },
        { id: 3, label: "部分支付", value: "part_pay" },
        { id: 4, label: "支付完成", value: "finish" },
        { id: 5, label: "支付取消", value: "cancel" },
      ],
      refundStateList: [
        // 退款状态
        { id: 1, label: "所有", value: "" },
        { id: 2, label: "无退款", value: "1" },
        { id: 3, label: "部分退款", value: "2" },
        { id: 4, label: "全额退款", value: "3" },
      ],
      multipleSelection: [],
      eventTab: "1",
      merchaList: [],
    };
  },
  created() {
    if (this.$store.state.buttonList) {
      this.$store.state.buttonList.forEach((e) => {
        if (e.type == "refund") {
          this.buttonRole = true;
        }
      });
    }
        //获取应用列表信息
        this.$http.get("/api/app/get").then((res) => {
        let appItem = res.data.find(
          (item) => item.id == this.$store.state.appId
        );
        this.merchaList = [
          {
            id: "",
            memberName: appItem.appName,
          },
        ];
        this.getmerList();
      });
    this.dataForm = JSON.parse(JSON.stringify(this.commandForm));
    this.handleQuery();
  },
  watch: {
    "$store.state.testLine": {
      handler() {
        if (this.$route.name == this.$options.name) {
          if (this.eventTab == "1") {
            this.handleQuery();
          } else if (this.eventTab == "2") {
            this.globalQuery();
          }
        }
      },
    },
    deep: true,
  },
  methods: {
    ...mapMutations(["changeLive"]),
        // 退款
        getmerList() {
      this.$http
        .get("/api/merchant/memberbase/listByAppIdAndTreeChain")
        .then((res) => {
          this.merchaList = [
            ...this.merchaList,
            ...res.data
          ]
        });
    },
        refundMoney(row) {
      let that = this;
      that
        .$confirm(
          "确认退款后，无需审核的将直接发起退款，需要审核的需审核人同意后方可发起退款，审核人拒绝则该笔订单状态不变，退款成功后退款金额将于7个工作日内原路原回。",
          "确认执行",
          {
            customClass: "confirm",
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            showClose: false,
            closeOnClickModal: false,
            closeOnPressEscape: false,
            type: "warning",
            center: true,
          }
        )
        .then(() => {
          that.payformId = row.id;
          that.refundRow = row;
          that.refundDialog = true;
          that.form.merchantOrderNo=that.refundRow.merchantOrderNo
            that.form.refundAmount = that.refundRow.fmtActualAmount;
        });
    },
    confirmRefund() {
      this.$refs.refundForm.validate((valid) => {
        if (valid) {
            // 单笔退款
            this.$http
              .post("/api/merchant/refundAudit/add", {
                orderId: this.payformId,
                reason: this.form.refundRemark,
              })
              .then((res) => {
                if (res.code === "0000") {
                  this.$message.success("已提交！");
                  this.$refs["refundForm"].resetFields();
                  this.refundDialog = false;
                  this.form.refundRemark = "";
                  if (this.eventTab == "1") {
                    this.handleQuery();
                  } else if (this.eventTab == "2") {
                    this.globalQuery();
                  }
                }
              });
        }
      });
    },
    exchangeEventTab() {
      if (this.eventTab == "1") {
        this.eventTab = "2";
        this.commandForm = {
          payformNo: this.commandForm.payformNo,
        };
        this.dataForm = JSON.parse(JSON.stringify(this.commandForm));
        this.globalQuery();
      } else {
        this.eventTab = "1";
        this.commandForm = {
          payformNo: this.commandForm.payformNo,
          status: "",
          refundState: "",
        memberId: "",
        serviceMerchantId: "",
          dateType: "1",
          date: [
            this.$moment().startOf("day").format("YYYY-MM-DD HH:mm:ss"),
            this.$moment().endOf("day").format("YYYY-MM-DD HH:mm:ss"),
          ],
        };
        this.dataForm = JSON.parse(JSON.stringify(this.commandForm));
        this.handleQuery();
      }
    },
    //重置操作
    resetFields() {
      this.resetForm("salesOrderForm");
    },
    handleDetails(rowData) {
      switch (this.activeKey) {
        case "1":
          this.$http
            .get(`/api/order/detail?id=${rowData.id}`)
            .then((res) => {
              if (res.code === "0000") {
                this.detailsInfo = res.data;
                this.drawer = true;
              }
            });
          break;
        default:
          break;
      }
    },
    handleQuery() {
      this.eventTab = "1";
      this.dataForm.payformNo = "";
      this.dataForm.gmtCreatedBegin = undefined;
      this.dataForm.gmtCreatedEnd = undefined;
      this.dataForm.payTimeBegin = undefined;
      this.dataForm.payTimeEnd = undefined;
      if (this.dataForm.date && this.dataForm.date.length) {
        if (this.dataForm.dateType === "1") {
          this.dataForm.gmtCreatedBegin = this.dataForm.date[0];
          this.dataForm.gmtCreatedEnd = this.dataForm.date[1];
        } else {
          this.dataForm.payTimeBegin = this.dataForm.date[0];
          this.dataForm.payTimeEnd = this.dataForm.date[1];
        }
      } else {
        this.dataForm.date = [
          this.$moment().startOf("day").format("YYYY-MM-DD HH:mm:ss"),
          this.$moment().endOf("day").format("YYYY-MM-DD HH:mm:ss"),
        ];
        this.dataForm.gmtCreatedBegin = this.dataForm.date[0];
        this.dataForm.gmtCreatedEnd = this.dataForm.date[1];
      }
      this.getDataList();
      this.getStatisticsInfo();
    },
    globalQuery() {
      this.eventTab = "2";
      this.getStatisticsInfo();
      this.getDataList();
    },
    //统计
    getStatisticsInfo() {
      this.$http.post("/api/order/statistics", this.dataForm).then((res) => {
        if (res.code === "0000") {
          this.info = res.data || {};
        }
      });
    },
    // 取消订单
    cancelOrder(row) {
      this.$http
        .post("/api/orderInfo/payformClose", {
          payformId: row.id,
          status: row.status,
        })
        .then((res) => {
          if (res.code === "0000") {
            this.$message.success("取消成功！");
            if (this.eventTab == "1") {
              this.handleQuery();
            } else if (this.eventTab == "2") {
              this.globalQuery();
            }
          }
        });
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
  },
};
</script>

<style scoped lang="scss">
.tabWrap {
  // height: 210px;
  height: 133px;
  // background: #ccc;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  .search {
    // position: absolute;
    // top: -60px;
    // right: 0;
    width: 466px;
  }
  .backWrap {
    height: 20px;
    position: absolute;
    bottom: 8px;
    right: 10px;
    display: flex;
    align-items: center;
    cursor: pointer;
    span {
      display: inline-block;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #03bfc6;
      margin-right: 10px;
    }
  }
}
.searchBtn {
  margin-top: 18px;
  background: #f5f5f5;
}
.switch {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}
// .search {
//   position: absolute;
//   right: 0;
//   top: -145px;
// }
.ml {
  margin-left: 20px;
}
.title {
  color: #4f595f;
  position: relative;
  font-size: 18px;
  font-weight: 500;
  line-height: 34px;
  margin-left: 10px;
}
.textBox {
  display: flex;
  .label {
    color: #869daa;
    font-size: 14px;
    width: 120px;
    margin-left: 10px;
    text-align: right;
  }
  .val {
    font-size: 14px;
    margin-left: 20px;
    color: #869daa;
    width: 700px;
  }
}
.pedding {
  color: #f69c1f;
}
.succeed {
  color: #07a555;
}
.failed {
  color: #f42b2b;
}

:deep(.leftSelect) {
  .el-input__inner {
    border-radius: 4px 0 0 4px;
  }
}
:deep(.search) {
  .el-input__inner {
    border-radius: 2px 0 0 2px;
    height: 38px;
    line-height: 38px;
  }
}
:deep(.searBtn) {
  .el-button--small {
    border-radius: 0 2px 2px 0;
    padding: 12px 24px;
  }
}
// .rightSelect {
//   border-radius: 0 4px 4px 0;
// }
</style>
